'''
Created on 2012-12-19

@author: j.chen
'''

def ip2num(ipString):
    if ipString is None:
        raise Exception("Invalid IP")

    try:
        octets = [octet.strip() for octet in ipString.split('.')]
    except Exception,e:
        raise e

    num = (int(octets[0])<<24) + (int(octets[1])<<16) + (int(octets[2])<<8) + int(octets[3])
    return num

def num2ip(numericIp):
    if numericIp is None or not (isinstance(numericIp,int) or isinstance(numericIp,long)):
        raise Exception("Invalid numeric IP. Must be an integer")
    return str(numericIp >> 24) + '.' + str((numericIp >> 16) & 255) + '.' + str((numericIp >> 8) & 255) + '.' + str(numericIp & 255)

def from_network(net):
    '''
    >>> '218.106.0.0/16' => ('218.106.0.0', '218.106.255.255')
    '''
    netaddr,bit = net.split('/')
    return (netaddr,num2ip(ip2num(netaddr)+(2<<(int(bit)-1))-1))
